﻿using ZeroSum.Domain.Repositories;
using ZeroSum.Exceptions;
using ZeroSum.Plugin.Authorization.Datas.Aggregates.MenuAggregate;

namespace ZeroSum.Plugin.Authorization.Datas.Services.Menus;

public class MenuBaseDomainService<TMenu> : IMenuBaseDomainService<TMenu> where TMenu : MenuBase
{
    protected readonly IRepository<TMenu, long> MenuRepository;

    public MenuBaseDomainService(IRepository<TMenu, long> menuRepository)
    {
        MenuRepository = menuRepository;
    }

    public virtual async Task<TMenu> AddAsync(TMenu entity, CancellationToken cancellationToken = default)
    {
        return await MenuRepository.AddAsync(entity);
    }

    public virtual async Task CheckRoleUpdate(long id)
    {
        var exist = await MenuRepository.AnyAsync(u => u.Id == id);
        if (!exist)
            throw AlreadyExistedException.Of($"编号为“{id}”的菜单不存在！")!;
    }

    public virtual async Task UpdateAsync(TMenu entity, CancellationToken cancellationToken = default)
    {
        await MenuRepository.UpdateAsync(entity);
    }

    public virtual async Task DeleteAsync(long id, CancellationToken cancellationToken = default)
    {
        await CheckRoleExist(id);
        var entity = await MenuRepository.GetAsync(id);
        await MenuRepository.RemoveAsync(entity);
    }

    public virtual async Task<TMenu> GetByIdAsync(long id, CancellationToken cancellationToken = default)
    {
        await CheckRoleExist(id);
        return await MenuRepository.GetAsync(id);
    }

    private async Task CheckRoleExist(long id)
    {
        var isExist = await MenuRepository.AnyAsync(u => u.Id == id);
        if (!isExist)
            throw AlreadyExistedException.Of($"编号为“{id}”的菜单不存在！")!;
    }
}